<template>
  <div>
    <p>
      <button class="btn btn-white btn-default btn-round" @click="add()">
        <i class="ace-icon fa fa-edit"></i>
        新增
      </button>
      &nbsp;
      <button class="btn btn-white btn-default btn-round" @click="list(1)">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
    </p>

    <pagination ref="pagination" :list="list"></pagination>

    <table id="simple-table" class="table  table-bordered table-hover">
      <thead>
        <tr>
          <th>id</th>
          <th>角色</th>
          <th>描述</th>
          <th>操作</th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="role in roles"
          :key="role.id"
          :index="role.id">
          <td>{{role.id}}</td>
          <td>{{role.name}}</td>
          <td>{{role.desc}}</td>

          <td>
            <div class="btn-group">
              <button class="btn btn-xs btn-danger" @click="editUser(role)">
                <i class="ace-icon fa fa-user bigger-120"></i>
              </button>
              <button class="btn btn-xs btn-danger" @click="editResource(role)">
                <i class="ace-icon fa fa-list bigger-120"></i>
              </button>
              <button class="btn btn-xs btn-info" @click="edit(role)">
                <i class="ace-icon fa fa-pencil bigger-120"></i>
              </button>
              <button class="btn btn-xs btn-danger" @click="del(role.id)">
                <i class="ace-icon fa fa-trash-o bigger-120"></i>
              </button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- Modal -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">角色表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">角色</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="role.name">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">描述</label>
                <div class="col-sm-10">
                    <input class="form-control" v-model="role.desc">
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="save()">保存</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Role & Resource Modal -->
    <div id="resource-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">角色资源管理配置</h4>
          </div>
          <div class="modal-body">
            <ul id="tree" class="ztree"></ul>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
            <button type="button" class="btn btn-primary" @click="saveResource()">保存</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Role & User Modal -->
    <div id="user-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">角色用户关联配置</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-6">
                <table id="user-table" class="table table-hover">
                  <tbody>
                  <tr v-for="user in users">
                    <td>{{user.loginName}}</td>
                    <td class="text-right">
                      <a v-on:click="addUser(user)" href="javascript:;" class="">
                        <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                      </a>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
              <div class="col-md-6">
                <table id="role-user-table" class="table table-hover">
                  <tbody>
                  <tr v-for="user in roleUsers">
                    <td>{{user.loginName}}</td>
                    <td class="text-right">
                      <a v-on:click="deleteUser(user)" href="javascript:;" class="">
                        <i class="ace-icon fa fa-trash blue"></i>
                      </a>
                    </td>
                  </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-white btn-default btn-round" data-dismiss="modal">
              <i class="ace-icon fa fa-times"></i>
              关闭
            </button>
            <button type="button" class="btn btn-white btn-info btn-round" v-on:click="saveUser()">
              <i class="ace-icon fa fa-plus blue"></i>
              保存
            </button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
  </div>
</template>

<script>
  import Pagination from "../../components/pagination"

  export default {
    name: "system-role",
    components: {Pagination},
    data() {
      return {
        role: {
          id: null,
          name: null,
          desc: null,
        },
        roles: [],
        resources: [],
        tree: {},
        users: [],
        roleUsers: []
      }
    },
    mounted() {
      let _this = this
      _this.list(1)
    },
    methods: {
      /**
       * 获取角色（分页）
       * @param page
       */
      list(page) {
        let _this = this

        Loading.show()

        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/role/list', {
          page: page,
          size: _this.$refs.pagination.size
        }).then((resp) => {
          if (resp.data.success) {
            _this.roles = resp.data.content.list
            _this.$refs.pagination.render(page, resp.data.content.total)

            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 添加角色（显示模态框）
       */
      add() {
        let _this = this
        _this.role = {
          id: null,
          name: null,
          desc: null,
        }
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 编辑角色（显示模态框）
       */
      edit(role) {
        let _this = this
        //  Object.assign(target, source)方法用于对象的合并，将源对象（source）的所有可枚举属性，复制到目标对象（target)
        Object.assign(_this.role, role)
        //  开启模态框
        $("#form-modal").modal('show')
      },

      /**
       * 保存角色
       */
      save() {
        let _this = this

        //  保存校验
        if (1 != 1
          || !Validator.require(_this.role.name, "角色")
          || !Validator.length(_this.role.name, "角色", 1, 50)
          || !Validator.require(_this.role.desc, "描述")
          || !Validator.length(_this.role.desc, "描述", 1, 100)
        ) {
          return;
        }

        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/role/save', _this.role).then((resp) => {
          if (resp.data.success) {
            //  关闭模态框
            $("#form-modal").modal('hide')
            //  刷新表格
            _this.list(1)
            Toast.success('保存成功！')
          } else {
            Toast.warning(resp.data.message)
          }
        })
      },

      /**
       * 删除角色（根据id）
       * @param id
       */
      del(id) {
        let _this = this
        Confirm.show('删除角色后不可恢复，是否确认删除？', () => {
          _this.$axios.delete(process.env.VUE_APP_SERVER + '/system/admin/role/delete/' + id).then((resp) => {
            if (resp.data.success) {
              //  刷新表格
              _this.list(1)
              Toast.success('删除成功！')
            }
          })
        })
      },

      /**
       * 编辑角色资源关联配置(打开模态框)
       */
      editResource(role) {
        let _this = this
        Object.assign(_this.role, role)
        _this.loadResource()
        //  开启模态框
        $("#resource-modal").modal('show')
      },

      /**
       * 加载资源树
       */
      loadResource() {
        let _this = this

        Loading.show()

        _this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/resource/list').then((resp) => {
          if (resp.data.success) {
            _this.resources = resp.data.content

            _this.initTree()  // 初始化树
            _this.listRoleResource(_this.role)
            Loading.hide()
          } else {
            Loading.hide()
          }
        })
      },

      /**
       * 保存角色资源关联配置
       */
      saveResource() {
        let _this = this
        let resourcesChosen = _this.tree.getCheckedNodes()  // 获得zTree上被勾选的资源

        let resourceIds = []
        for (let i = 0; i < resourcesChosen.length; i++) {
          resourceIds.push(resourcesChosen[i].id)
        }

        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/role/save-resource', {
          id: _this.role.id,
          resourceIds: resourceIds
        }).then((resp) => {
          if (resp.data.success) {
            Toast.success('保存成功!')
          } else {
            Toast.warning(resp.message)
          }
        })
      },

      /**
       * 根据角色id加载角色资源关联记录
       */
      listRoleResource(role) {
        let _this = this
        _this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/role/list-role-resource/' + role.id).then((resp) => {
          // 先清空所有勾选
          _this.tree.checkAllNodes(false)
          if (resp.data.success) {
            let resources = resp.data.content
            // 勾选查询到的节点
            for (let i = 0; i < resources.length; i++) {
              let node = _this.tree.getNodeByParam('id', resources[i])
              _this.tree.checkNode(node, true)
            }
          } else {
            Toast.warning(resp.message)
          }
        })
      },

      /**
       * 编辑角色用户关联配置(打开模态框)
       */
      editUser(role) {
        let _this = this
        Object.assign(_this.role, role)
        _this.listUser()
        //  开启模态框
        $("#user-modal").modal('show')
      },

      /**
       * 查询所有用户
       */
      listUser() {
        let _this = this
        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/user/list', {
          page: 1,
          size: 9999
        }).then((resp)=>{
          if (resp.data.success) {
            _this.users = resp.data.content.list
            _this.listRoleUser()
          } else {
            Toast.warning(resp.message)
          }
        })
      },

      /**
       * 角色中增加用户
       */
      addUser(user) {
        let _this = this
        //  如果当前要添加的用户在右边列表中已经有了, 则不用再添加
        let users = _this.roleUsers
        for (let i = 0; i < users.length; i++) {
          if (user === users[i]) {
            return
          }
        }
        _this.roleUsers.push(user)
      },

      /**
       * 角色中删除用户
       */
      deleteUser(user) {
        let _this = this
        Tool.removeObj(_this.roleUsers, user)
      },

      /**
       * 保存角色用户关联配置
       */
      saveUser() {
        let _this = this
        let users = _this.roleUsers

        let userIds = []  // 保存时只需要保存用户id
        for (let i = 0; i < users.length; i++) {
          userIds.push(users[i].id)
        }

        console.log('userIds' + userIds);

        _this.$axios.post(process.env.VUE_APP_SERVER + '/system/admin/role/save-user', {
          id: _this.role.id,
          userIds: userIds
        }).then((resp) => {
          if (resp.data.success) {
            Toast.success('保存成功!')
          } else {
            Toast.warning(resp.message)
          }
        })
      },

      /**
       * 根据角色id查询其关联的用户
       */
      listRoleUser() {
        let _this = this
        _this.roleUsers = []
        _this.$axios.get(process.env.VUE_APP_SERVER + '/system/admin/role/list-role-user/' + _this.role.id).then((resp) => {
          if (resp.data.success) {
            let userIds = resp.data.content
            // 根据后端传来的用户id, 在左侧被展示的用户里找对应的用户
            for (let i = 0; i < userIds.length; i++) {
              for (let j = 0; j < _this.users.length; j++) {
                if (userIds[i] === _this.users[j].id) {
                  _this.roleUsers.push(_this.users[i])
                }
              }
            }
          } else {
            Toast.warning(resp.message)
          }
        })
      },

      /**
       * 初始化zTree, 模板在zTree自带的demo里
       */
      initTree() {
        let _this = this
        let setting = {
          check: {
            enable: true
          },
          data: {
            simpleData: {
              idKey: 'id',
              pIdKey: 'parent', // 指明父节点在数据库里的名称, zTree默认叫pId
              rootPId: '',
              enable: true
            }
          }
        }

        _this.tree = $.fn.zTree.init($("#tree"), setting, _this.resources);

        //  展开所有节点
        _this.tree.expandAll(true)
      }
    }
  }
</script>

<style scoped>

</style>